#include "servermainwindow.h"
#include "ui_servermainwindow.h"

ServerMainwindow::ServerMainwindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::ServerMainwindow)
{
    ui->setupUi(this);

    ui->ui_TextBrowser->append(QString("[%1] 正在初始化状态栏...")
                               .arg(QDateTime::currentDateTime()
                                    .toString("yyyy-MM-dd hh:mm:ss")));
    SoftwareStatus *ui_StatusBar = new SoftwareStatus(this);
    ui->statusbar->addPermanentWidget(ui_StatusBar);
    connect(this, SIGNAL(signal_status_changed(int)), ui_StatusBar, SLOT(on_status_changed(int)));
    ui->ui_TextBrowser->append(QString("[%1] 初始化状态栏完成")
                               .arg(QDateTime::currentDateTime()
                               .toString("yyyy-MM-dd hh:mm:ss")));

//    f_UpdateUI();
}

ServerMainwindow::~ServerMainwindow()
{
    delete ui;

    if(m_server->isListening())
    {
        m_server->disconnect();
        m_server->close();
    }
}

void ServerMainwindow::f_UpdateUI()
{
    ui->ui_TextBrowser->append(QString("[%1] 正在读取配置信息...")
                               .arg(QDateTime::currentDateTime()
                               .toString("yyyy-MM-dd hh:mm:ss")));
    QSettings *config;
    try {
       config = new QSettings("./Config/Config.ini", QSettings::IniFormat);
    } catch (std::bad_alloc) {
        emit signal_status_changed(SoftwareStatus::Error);
        QMessageBox::critical(this, "错误", "申请内存空间失败!", QMessageBox::Yes);
        ui->ui_TextBrowser->append(QString("[%1] 申请内存空间失败")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss")));

        delete config;
        qApp->exit(-1);
    }

    if(config->contains("DATA/IP"))
    {
        m_IP = config->value("DATA/IP").toString();
        ui->ui_TextBrowser->append(QString("[%1] 读取到IP地址：<font color = \"orange\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_IP));
        ui->ui_LabelIP->setText(m_IP);
    }

    if(config->contains("DATA/PORT"))
    {
        m_Port = config->value("DATA/PORT").toString();
        ui->ui_TextBrowser->append(QString("[%1] 读取到端口地址：<font color = \"orange\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_Port));
        ui->ui_LabelPort->setText(m_Port);
    }
    delete config;
}

void ServerMainwindow::f_SetIPAddress(QString IP)
{
    m_IP = IP;
}

void ServerMainwindow::f_SetPort(QString Port)
{
    m_Port = Port;
}

void ServerMainwindow::f_StartTCP()
{
    m_server = new QTcpServer(this);
    connect(m_server, SIGNAL(newConnection()), this, SLOT(slot_AcceptConnection()));

    m_socket = new QTcpSocket();
    connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater()));

    if(!m_server->listen(QHostAddress(m_IP), m_Port.toUInt()))
    {
        emit signal_status_changed(SoftwareStatus::Error);
        ui->ui_TextBrowser->append(QString("[%1] <font color = \"red\">监听失败，原因是：%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_server->errorString()));
        return;

    }
    else
    {
        ui->ui_TextBrowser->append(QString("[%1] 开始监听IP地址：<font color = \"green\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_IP));
        ui->ui_TextBrowser->append(QString("[%1] 开始监听端口地址：<font color = \"green\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_Port));
    }
}


void ServerMainwindow::on_ui_BtnCleanBash_clicked()
{
    ui->ui_TextBrowser->clear();
}

void ServerMainwindow::on_action_IP_I_triggered()
{
    IPSet *widget_IPSet = new IPSet();
    if(!widget_IPSet->exec())
    {
        delete widget_IPSet;
        return;
    }
    else
    {
        QString IP = widget_IPSet->f_GetIPAddress();
        QString Port = widget_IPSet->f_GetPort();

        QSettings *config;
        try {
           config = new QSettings("./Config/Config.ini", QSettings::IniFormat);
        } catch (std::bad_alloc) {
            emit signal_status_changed(SoftwareStatus::Error);
            QMessageBox::critical(this, "错误", "申请内存空间失败!", QMessageBox::Yes);

            ui->ui_TextBrowser->append(QString("[%1] 申请内存空间失败")
                                       .arg(QDateTime::currentDateTime()
                                       .toString("yyyy-MM-dd hh:mm:ss")));

            delete config;
            qApp->exit(-1);
        }
        //停止监听原IP和端口
        if(m_server->isListening())
        {
            m_server->disconnect();
            m_server->close();
        }
        //丢弃原有TCP连接
        if(m_socket->isOpen())
        {
            m_socket->abort();
        }
        //改配置文件
        config->setValue("DATA/IP", IP);
        m_IP = IP;
        ui->ui_TextBrowser->append(QString("[%1] 修改IP地址为：<font color = \"blue\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_IP));

        config->setValue("DATA/PORT", Port);
        m_Port = Port;
        ui->ui_TextBrowser->append(QString("[%1] 修改端口地址为：<font color = \"blue\">%2</font>")
                                   .arg(QDateTime::currentDateTime()
                                   .toString("yyyy-MM-dd hh:mm:ss"))
                                   .arg(m_Port));
        delete config;
        //读配置文件
        f_UpdateUI();
        //监听修改后的IP和端口
        if(!m_server->listen(QHostAddress(m_IP), m_Port.toUInt()))
        {
            emit signal_status_changed(SoftwareStatus::Error);
            ui->ui_TextBrowser->append(QString("[%1] <font color = \"red\">监听失败，原因是：%2</font>")
                                       .arg(QDateTime::currentDateTime()
                                       .toString("yyyy-MM-dd hh:mm:ss"))
                                       .arg(m_server->errorString()));
            return;

        }
        else
        {
            m_socket = new QTcpSocket();
            connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater()));

            ui->ui_TextBrowser->append(QString("[%1] 开始监听新IP地址：<font color = \"green\">%2</font>")
                                       .arg(QDateTime::currentDateTime()
                                       .toString("yyyy-MM-dd hh:mm:ss"))
                                       .arg(m_IP));
            ui->ui_TextBrowser->append(QString("[%1] 开始监听新端口地址：<font color = \"green\">%2</font>")
                                       .arg(QDateTime::currentDateTime()
                                       .toString("yyyy-MM-dd hh:mm:ss"))
                                       .arg(m_Port));

            emit signal_status_changed(SoftwareStatus::Normal);
        }
    }
    delete widget_IPSet;
}

void ServerMainwindow::on_ui_BtnChangeIP_clicked()
{
    on_action_IP_I_triggered();
}

void ServerMainwindow::slot_AcceptConnection()
{
    m_socket = m_server->nextPendingConnection();
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(slot_AcceptData()));

    m_PeerIP = m_socket->peerAddress().toString();
    m_PeerPort = QString::number(m_socket->peerPort());
    ui->ui_TextBrowser->append(QString("[%1] 连入客户端 %2:%3")
                               .arg(QDateTime::currentDateTime()
                               .toString("yyyy-MM-dd hh:mm:ss"))
                               .arg(m_PeerIP).arg(m_PeerPort));

}

void ServerMainwindow::slot_AcceptData()
{
    QString message = QString::fromUtf8(m_socket->readAll());
    if(message.startsWith("$$") && message.endsWith("$$"))
    {
        m_socket->write("ACK");
    }
    else
    {
        m_socket->write("NAK");
        return;
    }

    message.remove(0, 2);
    message.chop(2);
    QStringList MessageList = message.split("#");

    ui->ui_TextBrowser->append(QString("[%1] 客户端 %2:%3 注册成功")
                               .arg(QDateTime::currentDateTime()
                               .toString("yyyy-MM-dd hh:mm:ss"))
                               .arg(m_PeerIP).arg(m_PeerPort));
    ui->ui_TextBrowser->append(QString("[姓名]：%1\n[班级]：%2\n[学号]：%3\n[年龄]：%4\n[密码(经md5加密)]：%5")
                               .arg(MessageList[4])
                               .arg(MessageList[1])
                               .arg(MessageList[2])
                               .arg(MessageList[3])
                               .arg(MessageList[0]));
}
